import React, { memo,useState,useRef,useEffect } from 'react'
import { Button, Card,Table,Modal ,Form,Input,message,Select } from 'antd';
import moment from "moment";
import { PlusCircleOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import { PAGE_SIZE } from "@/common";
import { reqAddUser,reqUserList,reqUpdateUser,reqDeleteUser} from "@/network";


const { Option } = Select;
const {confirm} = Modal

export default memo(function HjUser() {
  
  // state props
  const [isAddUserVisible, setIsAddUserVisible] = useState(false);//是否显示添加用户弹窗
  const [userList, setIsUserList] = useState([]);//用户列表数据
  const [roleList, setIsRoleList] = useState([]);//角色列表数据
  const [isLoading, setIsLoading] = useState(true);//是否加载完成数据
  const [userType, setUserType] = useState(0);//为了复用弹窗， 0：新增用户，1：修改用户
  const [currentUser, setCurrentUser] = useState({});//点击修改用户信息要获取的当前个人信息

    // other hooks
  const userFormRef = useRef()

  useEffect(() => {
    getUserList()
  }, []);

  // handle function

  // 发请求获取用户列表
  const getUserList = async()=>{
    const result = await reqUserList()
    // 取消loading
    setIsLoading(false)
    const {status,msg,data} = result
    if(status===0){
      setIsUserList(data.users)
      setIsRoleList(data.roles)
    }else {
      message.error(msg)
    }
  }
  // 发请求添加用户
  const getAddUser = async(userObj)=>{
    const result = await reqAddUser(userObj)
    const {data,status,msg} = result 
    if(status===0){
      message.success('添加用户成功')
      // 更新用户列表
      setIsUserList([...userList,data])

    }
    else{
      message.error(msg)
    }
  }

  // 发请求修改用户
  const getUpdateUser = async(userObj)=>{
    const result = await reqUpdateUser(userObj)
    const {status,msg} = result
    console.log(result);
    if(status===0){
      getUserList()
      message.success('修改用户成功')
    }else{
      message.error(msg)
    }
  }

  // 发请求删除用户
  const getDeleteUser = async(userId)=>{
    confirm({
    title: '提示：',
    icon: <ExclamationCircleOutlined />,
    content: '确定删除用户吗？',
    okText: '确认',
    cancelText: '取消',
    onOk:async()=>{
        const result = await reqDeleteUser(userId)
        const {status,msg} = result
        if(status===0){
          // 组件中删除当前id用户。也可以用getUserList() 拉一下
        const newUserList = userList.filter(item=>{
            return item._id !== userId
          })
          setIsUserList(newUserList)
          message.success('删除用户成功')
        }else{
          message.error(msg)
        }
      },
   });
    
  }

  // 点击确认添加/修改用户
   const handleUserOk = ()=>{
    //  验证form表单数据
     userFormRef.current.validateFields()
     .then((value)=>{
       if(!userType){
         // 发请求添加用户
         getAddUser(value)
       }else{
         const _id = currentUser._id
         const userObj = {
           _id,
          username:value.username,
          phone:value.phone,
          email:value.email,
          role_id:value.role_id,
        }
         // 发请求修改用户
         getUpdateUser(userObj)
       }
      
       if(userFormRef.current){
         // 做个延迟清除添加用户表单
        setTimeout(() => {
          userFormRef.current.resetFields()
           //  关闭添加用户弹窗
          setIsAddUserVisible(false)
        }, 500);
        
     }
    })
    .catch((error)=>{
       message.error('添加用户失败')
     })

    
    
    
  }
  // 点击取消添加用户
  const handleCancel = ()=>{
      setIsAddUserVisible(false)
      userFormRef.current.resetFields()
  }

  // 点击添加创建用户按钮
  const addUser = ()=>{
    setUserType(0)
   setIsAddUserVisible(true)
  }
  // 点击修改用户按钮
  const updateUser = (item)=>{
    setUserType(1)
    setCurrentUser(item)
    setIsAddUserVisible(true)
    
  }
  // 点击删除用户按钮
  const deleteUser = (item)=>{
    // 删除用户
      getDeleteUser(item._id)
  }
  const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '电话',
    dataIndex:'phone',
    key: 'phone',
  },
  {
    title: '注册时间',
    dataIndex:'create_time',
    key: 'create_time',
    render:(create_time)=>(create_time?moment(create_time).format('YYYY-MM-DD, h:mm:ss'):'')
  },
  {
    title: '所属角色',
    dataIndex:'role_id',
    key: 'role_id',
    render:(role_id)=>{
    const iten = roleList.find(item=>{
        return item._id ===role_id
      })
      if(iten)return iten.name
    }
  }
  ,
  {
    title: '操作',
    // dataIndex:'opera',
    key: 'opera',
    render:(item)=>(
      <div>
        <Button type="link" onClick={()=>updateUser(item)}>修改</Button>
        <Button type="link" onClick={()=>deleteUser(item)}>删除</Button>
      </div>
    )
  }
]

  return (
       <div>
      <Card 
          title={<Button type="primary" onClick={addUser} icon={<PlusCircleOutlined/>}>创建用户</Button>} >
           <Table 
                  dataSource={userList} 
                  columns={columns} 
                  rowKey="_id"
                  bordered
                  showHeader
                  loading={isLoading}
                   pagination={
                        {
                        pageSize:PAGE_SIZE,
                        defaultCurrent:1,
                      }}
                  />;
      </Card>
         {/* 创建用户的对话框 */}
           <Modal 
                title={userType?'修改用户':'创建用户'}
                visible={isAddUserVisible} 
                onOk={handleUserOk} 
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
                destroyOnClose //解決数据回显总是回显上一个数据的问题
                 >

                  <Form
                    name="userForm"
                    labelCol={{md:4}}
                    // labelAlign='left'
                    autoComplete="off"
                    ref={userFormRef}
                  >
                      <Form.Item
                         label="用户名"
                         name="username"
                         initialValue={currentUser.username}
                         rules={[{ required: true, message: '用户名必须输入！！' },{pattern:/^\w+$/,message:'用户名必须为字母、数字、下划线'}]}
                      >
                        <Input placeholder="输入用户名"/>
                      </Form.Item>
                       <Form.Item
                         label="密码"
                         name="password"
                         rules={[{ required: true, message: '密码必须输入！！' },{pattern:/^\w+$/,message:'密码必须为字母、数字、下划线'}]}
                      >
                        <Input placeholder="输入密码"  type="password"/>
                      </Form.Item>
                       <Form.Item
                         label="手机号"
                         name="phone"
                         initialValue={currentUser.phone}
                         rules={[
                           { required: true, message: '手机号必须输入！！' },
                           {pattern:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,message:'请输入正确的手机号'}]}
                      >
                        <Input placeholder="输入手机号" />
                      </Form.Item>
                      <Form.Item
                         label="邮箱"
                         name="email"
                         initialValue={currentUser.email}
                         rules={[{ required: true, message: '邮箱必须输入！！' },{pattern:/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,message:'请输入邮箱格式'}]}
                      >
                        <Input placeholder="输入邮箱" />
                      </Form.Item>
                       <Form.Item
                        label="角色"
                        name="role_id"
                        initialValue={currentUser.role_id}
                      >
                          <Select placeholder="请选择角色">
                           {
                             roleList.map(item=>{
                               return (
                                  <Option key={item._id}>{item.name}</Option>
                               )
                             })
                           }
                          </Select>
                      </Form.Item>     
                   </Form>
            </Modal>
     </div>
    )
})